package com.tanhua.server.service;

import com.tanhua.autoconfig.templates.AipFaceTemplate;
import com.tanhua.autoconfig.templates.HuanXinTemplate;
import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.dubbo.api.UserApi;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.db.Freeze;
import com.tanhua.model.db.User;
import com.tanhua.model.db.UserInfo;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.server.exceptions.BusinessException;
import com.tanhua.utils.JwtUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Service
public class UserService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @DubboReference
    private UserApi userApi;

    @DubboReference
    private UserInfoApi userInfoApi;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipFaceTemplate aipFaceTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    /**
     * 用户登录或注册
     */
    public Map loginVerification(String phone, String code) {

        //判断用户是否冻结，根据手机号查出用户
        User user = userApi.findByMobile(phone);
        if (user != null) { //等于null是新用户 不存在冻结
            Long id = user.getId();
            UserInfo userInfo = userInfoApi.findById(id);
            //String userStatus = userInfo.getUserStatus();
            if (userInfo.getUserStatus().equals("2")) {//用户状态,1为正常，2为冻结
                Integer freezingRange = userInfo.getFreezingRange();
                if (freezingRange == 1) {
                    throw new BusinessException(ErrorResult.myError("该账号被冻结"));
                }
            }
        }
        //1.对验证码进行判断
        //1.1 从Redis中获取。发送的验证码数据
        String redisCode = redisTemplate.opsForValue().get("CODE" + phone);
        //1.2 比较Redis和用户输入的是否一致
        if (StringUtils.isEmpty(redisCode) || !redisCode.equals(code)) {
            //1.3 不一致，抛出异常
            ErrorResult result = ErrorResult.loginError();
            throw  new BusinessException(result);//抛出自定义异常，指定一些返回到的数据
        }
        //1.4 一致，将Redis中的删除
        redisTemplate.delete("CODE" + phone);
        //2.根据手机号查询用户
        //User user = userApi.findByMobile(phone);
        Boolean isNew = false;//老用户
        String type = "0101";
        if (user == null) {//注册
            //3.不存在，保存用户信息
            user = new User();
            user.setMobile(phone);
            user.setPassword("123456");
            Long userId = userApi.save(user);
            user.setId(userId);
            isNew = true;//新用户
            //将用户数据注册到环信
            huanXinTemplate.createUser("hx" + userId, "123456");
            //更新用户表，更新环信账号和密码字段
            user.setHxUser("hx" + userId);
            user.setHxPassword("123456");
            userApi.update(user);
            type = "0102";
        }

        //向RabbleMQ发送消息
        //将需要保存的数据，存入到map
//        Map map1 = new HashMap();
//        map1.put("userId", user.getId());
//        map1.put("type", type);
//        map1.put("logTime", new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
//        String message = JSON.toJSONString(map1);
//        //路由key：操作的类型（用户登录/注册：用户操作，动态操作...）
//        rabbitTemplate.convertAndSend("tanhua.log.exchange","log.user",message);//四个参数
        mqMessageService.sendLogMessage(user.getId(), type, "log.user", null);

        //4.生成token
        Map map = new HashMap();
        map.put("id", user.getId());
        map.put("mobile", user.getMobile());
        String token = JwtUtils.getToken(map);//存入token的数据
        //5.构造返回值Map
        Map retMap = new HashMap();
        retMap.put("token", token);
        retMap.put("isNew", isNew);
        return retMap ;
    }



    /**
     * 完善用户信息
     */
    public void loginReginfo(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /**
     * 上传用户头像
     * @param userId
     * @param headPhoto
     */
    public void head(Long userId, MultipartFile headPhoto) throws IOException {
        //上传文件到阿里云oss，获取URL地址
        String url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());

        //根据图片的URL，判断图片中是否具有人脸
        boolean detect = aipFaceTemplate.detect(url);
        //不包含人脸，抛出异常
        if (!detect) {
            ErrorResult result = ErrorResult.faceError();
            throw new BusinessException(result);
        }
        //包含人脸更新数据库 ----使用mp更新，只需需要new对象，设置id和需要更新的字段就行
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setAvatar(url);
        userInfoApi.update(userInfo);
    }
}
